package cn.ctodb.wxmp.web.rest;

import com.codahale.metrics.annotation.Timed;
import cn.ctodb.wxmp.service.MpService;
import cn.ctodb.wxmp.web.rest.util.HeaderUtil;
import cn.ctodb.wxmp.web.rest.util.PaginationUtil;
import cn.ctodb.wxmp.service.dto.MpDTO;

import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.inject.Inject;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

import static org.elasticsearch.index.query.QueryBuilders.*;

/**
 * REST controller for managing Mp.
 */
@RestController
@RequestMapping("/api")
public class MpResource {

    private final Logger log = LoggerFactory.getLogger(MpResource.class);
        
    @Inject
    private MpService mpService;

    /**
     * POST  /mps : Create a new mp.
     *
     * @param mpDTO the mpDTO to create
     * @return the ResponseEntity with status 201 (Created) and with body the new mpDTO, or with status 400 (Bad Request) if the mp has already an ID
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PostMapping("/mps")
    @Timed
    public ResponseEntity<MpDTO> createMp(@RequestBody MpDTO mpDTO) throws URISyntaxException {
        log.debug("REST request to save Mp : {}", mpDTO);
        if (mpDTO.getId() != null) {
            return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert("mp", "idexists", "A new mp cannot already have an ID")).body(null);
        }
        MpDTO result = mpService.save(mpDTO);
        return ResponseEntity.created(new URI("/api/mps/" + result.getId()))
            .headers(HeaderUtil.createEntityCreationAlert("mp", result.getId().toString()))
            .body(result);
    }

    /**
     * PUT  /mps : Updates an existing mp.
     *
     * @param mpDTO the mpDTO to update
     * @return the ResponseEntity with status 200 (OK) and with body the updated mpDTO,
     * or with status 400 (Bad Request) if the mpDTO is not valid,
     * or with status 500 (Internal Server Error) if the mpDTO couldnt be updated
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PutMapping("/mps")
    @Timed
    public ResponseEntity<MpDTO> updateMp(@RequestBody MpDTO mpDTO) throws URISyntaxException {
        log.debug("REST request to update Mp : {}", mpDTO);
        if (mpDTO.getId() == null) {
            return createMp(mpDTO);
        }
        MpDTO result = mpService.save(mpDTO);
        return ResponseEntity.ok()
            .headers(HeaderUtil.createEntityUpdateAlert("mp", mpDTO.getId().toString()))
            .body(result);
    }

    /**
     * GET  /mps : get all the mps.
     *
     * @param pageable the pagination information
     * @return the ResponseEntity with status 200 (OK) and the list of mps in body
     * @throws URISyntaxException if there is an error to generate the pagination HTTP headers
     */
    @GetMapping("/mps")
    @Timed
    public ResponseEntity<List<MpDTO>> getAllMps(@ApiParam Pageable pageable)
        throws URISyntaxException {
        log.debug("REST request to get a page of Mps");
        Page<MpDTO> page = mpService.findAll(pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/mps");
        return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
    }

    /**
     * GET  /mps/:id : get the "id" mp.
     *
     * @param id the id of the mpDTO to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the mpDTO, or with status 404 (Not Found)
     */
    @GetMapping("/mps/{id}")
    @Timed
    public ResponseEntity<MpDTO> getMp(@PathVariable Long id) {
        log.debug("REST request to get Mp : {}", id);
        MpDTO mpDTO = mpService.findOne(id);
        return Optional.ofNullable(mpDTO)
            .map(result -> new ResponseEntity<>(
                result,
                HttpStatus.OK))
            .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }

    /**
     * DELETE  /mps/:id : delete the "id" mp.
     *
     * @param id the id of the mpDTO to delete
     * @return the ResponseEntity with status 200 (OK)
     */
    @DeleteMapping("/mps/{id}")
    @Timed
    public ResponseEntity<Void> deleteMp(@PathVariable Long id) {
        log.debug("REST request to delete Mp : {}", id);
        mpService.delete(id);
        return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert("mp", id.toString())).build();
    }

    /**
     * SEARCH  /_search/mps?query=:query : search for the mp corresponding
     * to the query.
     *
     * @param query the query of the mp search 
     * @param pageable the pagination information
     * @return the result of the search
     * @throws URISyntaxException if there is an error to generate the pagination HTTP headers
     */
    @GetMapping("/_search/mps")
    @Timed
    public ResponseEntity<List<MpDTO>> searchMps(@RequestParam String query, @ApiParam Pageable pageable)
        throws URISyntaxException {
        log.debug("REST request to search for a page of Mps for query {}", query);
        Page<MpDTO> page = mpService.search(query, pageable);
        HttpHeaders headers = PaginationUtil.generateSearchPaginationHttpHeaders(query, page, "/api/_search/mps");
        return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
    }


}
